<template>
    <el-table :data="tableData" stripe style="width: 100%" border @row-click="handleRowClick">
        <el-table-column label="微博动态" align="center">
            <template #default="scope">
                <div class="weibo-card">
                    <!-- 头像及发布者信息区域 -->
                    <div class="weibo-card__header">
                        <div class="avatar-container">
                            <img :src="'/img'+scope.row.tx" alt="avatar" class="weibo-card__avatar" />
                            <span class="weibo-card__nickname">{{ scope.row.yhm }}</span>
                        </div>
                        <div class="header-content">
                            <div class="weibo-card__meta">
                                {{ scope.row.time }} 来自 微博网页版
                            </div>
                            <div class="weibo-card__meta">
                                标题# {{ scope.row.title }}
                            </div>
                        </div>
                    </div>

                    <!-- 动态内容区域 -->
                    <div class="weibo-card__content">
                        {{ scope.row.text }}
                        <div class="weibo-card__image" v-if="scope.row.url && scope.row.url.trim()">
                            <img
                                    v-for="(imgUrl, index) in scope.row.url.split(',')"
                                    :key="index"
                                    :src="'/img'+imgUrl.trim()"
                                    alt="weibo-img"
                                    class="imgs"
                            />
                        </div>
                    </div>

                    <!-- 互动按钮区域（含点赞/收藏状态） -->
                    <div class="weibo-card__actions">
            <span class="weibo-card__action">
              <el-icon class="el-icon"><ChatDotRound /></el-icon>
              {{ scope.row.commentCount || 0 }}
            </span>

                        <!-- 点赞按钮（带状态） -->
                        <span class="weibo-card__action" @click="handleLike(scope.row)">
              <el-icon class="el-icon" :class="{ 'liked': scope.row.isLiked }"><Pointer /></el-icon>
              {{ scope.row.likeCount || 0 }}
            </span>

                        <!-- 收藏按钮（带状态） -->
                        <span class="weibo-card__action" @click="handleCollect(scope.row)">
              <el-icon class="el-icon" :class="{ 'collected': scope.row.isCollected }"><StarFilled /></el-icon>
              {{ scope.row.collectCount || 0 }}
            </span>

                        <span class="weibo-card__action">
              <el-icon class="el-icon"><View /></el-icon>
              {{ scope.row.browse || 0 }}
            </span>
                    </div>
                </div>
            </template>
        </el-table-column>
    </el-table>
</template>

<script setup lang="ts">
import axios from 'axios';
import { ref, onMounted } from 'vue';
// 引入 Element Plus 图标，按需添加
import {ChatDotRound, StarFilled, Share, Pointer, View} from '@element-plus/icons-vue';
import router from "../router"

const tableData = ref([]);

onMounted(() => {
  doList();
  doListWithAllCount().then(() => {
      initAllPostStatus();
  });
});

const doList = async () => {
  const { data } = await axios.get('/api/postAndUser/new');
  console.log(data);
  tableData.value = data;
};
const handleRowClick = (row) => {
  router.push(`/poster?id=${row.id}`)
}

//==================
import { ChatDotRound, StarFilled, View, Pointer } from '@element-plus/icons-vue';

import { useUserStore } from "@/stores/user";

// 用户信息（获取当前登录用户ID）
const userStore = useUserStore();
const userId = userStore.id;

/**
 * 加载帖子列表数据
 * 为每个帖子添加isLiked和isCollected初始状态
 */
const doListWithAllCount = async () => {
    const { data } = await axios.get('/api/postAndUser/allCount/time');
    // 为每个帖子初始化点赞/收藏状态（默认未操作）
    tableData.value = data.map(post => ({
        ...post,
        isLiked: false,
        isCollected: false
    }));
    return tableData.value;
};

/**
 * 初始化所有帖子的点赞/收藏状态
 * 遍历列表调用接口查询每个帖子的状态
 */
const initAllPostStatus = async () => {
    if (!userId) return; // 未登录则不初始化状态

    for (const post of tableData.value) {
        // 并行请求当前帖子的点赞和收藏状态（优化加载速度）
        await Promise.all([
            getLikeStatus(post),
            getCollectStatus(post)
        ]);
    }
};

/**
 * 获取单个帖子的点赞状态
 * @param post 帖子对象
 */
const getLikeStatus = async (post) => {
    const postId = post.id;
    if (!postId) return;

    try {
        const { data: likeData } = await axios.get(`/api/like/${postId}/${userId}`);
        post.isLiked = !!likeData; // 存在记录则标记为已点赞
    } catch (error) {
        console.error(`帖子${postId}点赞状态查询失败:`, error);
    }
};

/**
 * 获取单个帖子的收藏状态
 * @param post 帖子对象
 */
const getCollectStatus = async (post) => {
    const postId = post.id;
    if (!postId) return;

    try {
        const { data: status } = await axios.get(`/api/collect/status/user/${userId}/post/${postId}`);
        post.isCollected = status; // 直接使用后端返回的布尔值
    } catch (error) {
        console.error(`帖子${postId}收藏状态查询失败:`, error);
    }
};

/**
 * 处理点赞操作
 * @param post 当前点击的帖子对象
 */
const handleLike = async (post) => {
    const postId = post.id;
    if (!postId || !userId) {
        alert("请先登录");
        return;
    }

    try {
        if (post.isLiked) {
            // 取消点赞
            const res = await axios.delete(`/api/like/${postId}/${userId}`);
            if (res.data > 0) {
                post.isLiked = false;
                post.likeCount = (post.likeCount || 0) - 1;
            }
        } else {
            // 新增点赞
            const likeData = {
                postId: postId,
                userId: userId,
                time: new Date().toISOString().replace('T', ' ').slice(0, 19)
            };
            const res = await axios.post('/api/like', likeData);
            if (res.data > 0) {
                post.isLiked = true;
                post.likeCount = (post.likeCount || 0) + 1;
            }
        }
    } catch (error) {
        console.error(`帖子${postId}点赞操作失败:`, error);
        alert("操作失败，请重试");
    }
};

/**
 * 处理收藏操作
 * @param post 当前点击的帖子对象
 */
const handleCollect = async (post) => {
    const postId = post.id;
    if (!postId || !userId) {
        alert("请先登录");
        return;
    }

        if (post.isCollected) {
            // 取消收藏：先查询收藏ID再删除
            const { data: collectId } = await axios.get(`/api/collect/user/${userId}/post/${postId}`);
            if (!collectId) {
                alert("未找到收藏记录");
                return;
            }
            const res = await axios.delete(`/api/collect/${collectId}`);
            if (res.data > 0) {
                post.isCollected = false;
                post.collectCount = (post.collectCount || 0) - 1;
            }
        } else {
            // 新增收藏
            const collectData = {
                userId: userId,
                postId: postId,
                time: new Date().toISOString().replace('T', ' ').slice(0, 19)
            };
            const res = await axios.post('/api/collect', collectData);
            if (res.data > 0) {
                post.isCollected = true;
                post.collectCount = (post.collectCount || 0) + 1;
            }
        }
};
</script>

<style scoped>
.weibo-card {
  display: flex;
  flex-direction: column;
  background-color: #fff;
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}
.weibo-card__header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}
.weibo-card__avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 4px;
}
.weibo-card__info {
  display: flex;
  flex-direction: column;
}
.weibo-card__nickname {
  font-weight: bold;
  color: #333;
}
.weibo-card__meta {
  font-size: 12px;
  color: #999;
}
.weibo-card__content {
  margin: 8px 0;
  color: #333;
  line-height: 1.6;
}
.weibo-card__image {
  margin-top: 8px;
}
.weibo-card__image img {
  max-width: 200px;
  border-radius: 4px;
}
.weibo-card__actions {
    display: flex;
    gap: 24px;
    color: #666;
    margin-top: 12px;
    justify-content: center;
}

.weibo-card__action {
    display: flex;
    align-items: center;
    gap: 4px;
    transition: color 0.2s;
    cursor: pointer;
}

.weibo-card__action:hover {
    color: #409eff;
}
.imgs{
  width: 133px;
  height: 133px;
  margin: 0 2px;
}
.el-icon{
  font-size: 20px;
}

/* 点赞和收藏状态样式 */
::v-deep .weibo-card__action .liked {
    color: #ff4d4f; /* 点赞后红色 */
}

::v-deep .weibo-card__action .collected {
    color: #faad14; /* 收藏后金色 */
}
</style>